package other.edan.system.client;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.exception.CacheException;
import com.rkhd.platform.sdk.exception.CustomConfigException;
import com.rkhd.platform.sdk.http.CommonData;
import com.rkhd.platform.sdk.http.CommonHttpClient;
import com.rkhd.platform.sdk.http.HttpResult;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.service.CacheService;
import com.rkhd.platform.sdk.service.CustomConfigService;
import org.apache.commons.lang.StringUtils;
import other.edan.system.utils.ResultBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 理邦k3对接
 * @Author: 黎炎松
 * @Date: 2024/6/12 10:21
 */
public class EdanK3Utils {
    private static String BASE_URL = "http://visit.edan.com.cn:9090"; // 域名
    private static String GET_TOKEN_URL = BASE_URL + "/edan/loginWeekly"; // 获取token
    public static String ADD_UP_ACCOUNT_URL = BASE_URL + "/edan/thirdParty/crm/customer/insertOrUpdate"; // 新增、修改客户
    public static String ADD_UP_ACCOUNT_TEST_URL = BASE_URL + "/edan/thirdParty/crm/test/customer/insertOrUpdate"; // 新增、修改客户(测试环境)
    public static String GET_PRODUCT_URL = BASE_URL + "/edan/thirdParty/crm/product/getProductInfo"; // 获取产品

    //public static String ADD_MARKET_APPLY_URL = BASE_URL + "/edan/thirdParty/crm/marketApply/insert"; // 新增市场活动费用申请单
    //public static String UP_MARKET_APPLY_URL = BASE_URL + "/edan/thirdParty/crm/marketApply/update"; // 更新市场活动费用申请单

    public static String ADD_MARKET_APPLY_URL = BASE_URL + "/edan/thirdParty/crm/marketApplyTest/insert"; // 新增市场活动费用申请单
    public static String UP_MARKET_APPLY_URL = BASE_URL + "/edan/thirdParty/crm/marketApplyTest/update"; // 更新市场活动费用申请单

    public static String GET_EHR_DEPART_URL = BASE_URL + "/edan/thirdParty/hr/getHrDepartmentChildren"; // 获取明基部门信息
    public static String GET_EHR_DEPART_USER_URL = BASE_URL + "/edan/thirdParty/hr/getHrAccountInfos"; // 获取明基部门下的人员信息
    public static String GET_EDAN_ACCOUNT_URL = BASE_URL + "/edan/thirdParty/crm/currency/getCurrencyInfo"; // 获取理邦客户信息
    public static String GET_SALES_ORDER_URL = BASE_URL + "/edan/thirdParty/crm/seorder/getSEOrderInfo"; // 获取销售订单信息
    public static String GET_SALES_OUT_URL = BASE_URL + "/edan/thirdParty/crm/stock/getICStockBillInfo"; // 获取销售出库单信息
    public static String GET_BIG_PROJECT_URL = BASE_URL + "/edan/thirdParty/crm/project/getBigProjectTR"; // 获取大项目 TR 日期信息
    private static final Logger logger = LoggerFactory.getLogger();
    private static final CacheService cacheService = CacheService.instance();
    private static final String TOKEN_KEY = "K3_TOKEN";


    // k3 信息配置
    private static Map<String, String> k3Config;

    static {
        try {
            CustomConfigService instance = CustomConfigService.instance();
            k3Config = instance.getConfigSet("Edan_k3");
            if (k3Config == null) {
                k3Config = new HashMap<>();
            }
        } catch (CustomConfigException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws CustomConfigException, CacheException {
        new EdanK3Utils().getToken();
    }

    /**
     * 发送get请求
     * @param paramsMap
     * @param reqUrl
     * @return
     */
    public static ResultBody sendGet(Map<String, Object> paramsMap, String reqUrl, String token) throws CacheException {

        // 拼接 URL
        if (StringUtils.isBlank(token)) {
            token = getToken();
        }
        String params = "";
        for (String key : paramsMap.keySet()) {
            if (params == "") {
                params = "?" + key + "=" + paramsMap.get(key);
            } else {
                params += "&" + key + "=" + paramsMap.get(key);
            }
        }

        // 进行转码
        params = params.replaceAll(" ", "%20");

        CommonData build = CommonData.newBuilder().callString(reqUrl + params)
                .callType("GET")
                .header("token", token)
                .build();
        HttpResult execute = CommonHttpClient.instance(30000, 30000).execute(build);
        String result = execute.getResult();
        System.out.println("result = " + result);
        JSONObject response = JSONObject.parseObject(result);
        Integer code = response.getInteger("code");
        String msg = response.getString("msg");
        // 判断是否是缓存过期
        if (code == 102 || msg.equals("token无效")) {
            // 重新发起请求
            logger.error("K3 token过期，重新发起请求");
            cacheService.delete(TOKEN_KEY);
            return sendGet(paramsMap, reqUrl, "");
        } else if (code != 100) {
            return ResultBody.error(msg);
        }
        //JSONObject data = response.getJSONObject("data");
        Object data = response.get("data");
        return ResultBody.success(data);
    }

    /**
     * 发送post请求
     * @param reqData
     * @param reqUrl
     * @return
     */
    public static ResultBody sendPost(JSONObject reqData, String reqUrl, String token) throws CacheException {
        if (StringUtils.isBlank(token)) {
            token = getToken();
        }
        CommonData build = CommonData.newBuilder().callString(reqUrl)
                .callType("POST")
                .header("token", token)
                .body(JSONObject.toJSONString(reqData))
                .formType("")
                .build();
        HttpResult execute = CommonHttpClient.instance().execute(build);
        String result = execute.getResult();
        System.out.println("result = " + result);
        JSONObject response = JSONObject.parseObject(result);
        Integer code = response.getInteger("code");
        String msg = response.getString("msg");
        // 判断是否是缓存过期
        if (code == 102 || msg.equals("token无效")) {
            // 重新发起请求
            logger.error("K3 token过期，重新发起请求");
            cacheService.delete(TOKEN_KEY);
            return sendPost(reqData, reqUrl, "");
        } else if (code != 100) {
            return ResultBody.error(msg);
        }

        Object data = response.getString("data");
        return ResultBody.success(msg, data);
    }

    public static String getToken() throws CacheException {

        // 判断缓存中是否存在
        String token = cacheService.get(TOKEN_KEY);
        if (StringUtils.isNotBlank(token)) {
            logger.info("获取缓存token: " + token);
            return token;
        }

        String userCode = k3Config.getOrDefault("userCode", "xiaoshouyi");
        String userPassword = k3Config.getOrDefault("userPassword",
                "hqGzNM3fuH5e0FAaPH3p9Vrixsxfn8m4OTqyim5+LnhnE7WtYu9+" +
                        "FvqtlKvqncSI07PrnCAFOTwvGudyji2z7enKittBhNiBz/Hj/OvT8vc" +
                        "D9EdcmKO4bk0/M6By4Cu2LXTDEFAPZilvKR89XNjMLl7gEkLvjCFMFsc" +
                        "L2wTeUdrbpIb1igNb8CVHTgjlV+90EFweAk/nyLQ3LScxyWPu12Xq/dXbb" +
                        "07uiPPGsY2NPay2eVhjZQAhoA+UwwBTdZqbXssZbuMO6idWxKMKwCH2bXC" +
                        "cUhW9f84Ux3eo2TVzwC7XBcpq2GQoCEHq1O0UN9Hgx5rHWUV0hC6mQr+d97yjqQ==");

        Map<String, Object> reqFormData = new HashMap<>();
        reqFormData.put("userCode", userCode);
        reqFormData.put("userPassword", userPassword);
        // 发送请求
        CommonData build = CommonData.newBuilder().callString(GET_TOKEN_URL)
                .callType("POST")
                .formData(reqFormData)
                .build();

        HttpResult execute = CommonHttpClient.instance().execute(build);
        String result = execute.getResult();
        System.out.println("getToken = " + result);
        JSONObject response = JSONObject.parseObject(result);
        Integer code = response.getInteger("code");
        if (!Objects.equals(code, 200)) {
            return null;
        }
        token = response.getString("tok");

        // 设置缓存值
        cacheService.set(TOKEN_KEY, token);
        return token;
    }


}
